const fs = require('fs')
const axios = require('axios')
const path = require('path')
const request = require('request')
const md5 = require('md5-file')

const targetBaseUrl = 'http://www.jnaw.top/cwbuFile/picc-json'
//const targetBaseUrl = 'http://192.168.55.100/cwbu/picc-json-www'
const stepsFileUrl = '/steps.json'
const stepListFileUrl = '/step_list.json'
const localFile = './steps.json'

const dirPath = path.join(__dirname, "ab")

let allNum = 0;
let downNum = 0;
let steps = {}
let stepList = {}


let combine = async _ => {

    await axios.get(targetBaseUrl + stepsFileUrl).then(res => steps = res.data)
    await axios.get(targetBaseUrl + stepListFileUrl).then(res => stepList = res.data)

    for (let i in stepList.steps) {
        let item = stepList.steps[i]
        //let target = Object.assign(item, steps['step' + item.name])
        let target = steps['step' + item.name]

        allNum++
        check(target)

        let ar = target['ar'] || {}
        let assets = ar['assets'] || []
        for (let a in assets) {
            if (!assets[a].url) {
                continue;
            }
            let obj = assets[a]
            allNum++
            check(obj)
        }
    }


}

let check = target => {
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath)
    }

    let file = path.join(dirPath, target.name)
    let out = fs.createWriteStream(file)

    console.log(target.name + ' downloading...')
    request(target.url).pipe(out).on('close', err => {
        const hash = md5.sync(file)
        downNum++
        if (hash != target.md5) {
            console.log('ERROR: ' + target.name + ' check failed... old:' + target.md5 + ' != ' + hash)
            target.md5 = hash
        } else {
            console.log(target.name + ' done')
        }

        if (downNum == allNum) {
            let list = JSON.stringify(steps, null, 4)
            // 写入
            fs.writeFile(localFile, list, function (err) {
                if (err) {
                    throw err;
                }
                console.log('写入成功' + localFile);
            });
        }
    })
}

combine()
